#include "TuxSpyPanel.h"
#include "TuxedoSite.h"
#include "FusionSpyResource.h"
#include "TuxSpyTuxAlarmDlg.h"

#include <wx/sstream.h>
#include <wx/xml/xml.h>
#include <wx/stdpaths.h>

#define SOCKET_ID 0x239
#define ID_TIMER 1024

enum {
	wxID_MODIFY,
	wxID_SHUTDOWN
};
/*
enum {
	DISABLE=0,	ENABLE,	COLOR, LONGBUSY,LONGIDLE, SVRDIED
};
*/

#define DISABLE  0      ///< 
#define ENABLE 0x0001
#define LONGBUSY  0x0002  ///< 
#define LONGIDLE  0x0004  ///< 
#define SVRDIED  0x0008  ///< 
#define COLOR  0x0010  ///< 


wxString status_list_value[] = {
	wxT("Tuxedo Ver :"),
	wxT("System Boot:"),
	wxT("Last Update:"),
	wxT("Run Servers:"),
	wxT("Run  Queues:"),
	wxT("Run Clients:"),
	wxT("OS Version :"),
	wxT("CPU   Idle :"),
	wxT("MEM   Free :"),
	wxT("Agent Ver  :"),
	wxT("")
};

wxString server_list_column[] = {
	wxT("Prog Name"),
	wxT("Queue Name"),
	wxT("Process ID"),
	wxT("RqDone"),
	wxT("SvrMin"),
	wxT("SvrMax"),
	wxT("CurrentService"),
	wxT("Memory Use"),
	wxT("")
};

wxString queue_list_column[] = {
	wxT("Prog Name"),
	wxT("IPCS QueueID"),
	wxT("Server Count"),
	wxT("Queued"),
	wxT("")
};

wxString client_list_column[] = {
	wxT("Client Name"),
	wxT("Client PID"),
	wxT("Client Addr"),
	wxT("Client Status"),
	wxT("Connection Time"),
	wxT("")
};
int SortByQueued(TuxedoQueue** Que1, TuxedoQueue** Que2);
int SortByRqDone(TuxedoServer** Svr1, TuxedoServer** Svr2);


BEGIN_EVENT_TABLE(TuxSpyPanel, TuxPanel)
	EVT_BUTTON(ID_MAIN_CONTROL, TuxSpyPanel::OnControl)
	EVT_TIMER(ID_TIMER, TuxSpyPanel::OnTimer)
	EVT_SOCKET(SOCKET_ID, TuxSpyPanel::OnSocketEvent)
END_EVENT_TABLE()

TuxSpyPanel::TuxSpyPanel( wxWindow* parent )
	: TuxPanel( parent )
{
	m_IsStart = false;
	m_quefilter = wxT("*");	m_svrfilter = wxT("*");
	m_chssvrfilter = 0;m_chsquefilter =0;
	//m_tuxalarm.Queued = wxT("5");

	m_logfile.Open( _T("FusionSpyLog.txt"), _T("w+"));

	LogFile =  new wxLogStderr(m_logfile.fp());
	LogFile->SetTimestamp(_T("[%d/%m/%y %H:%M:%S] "));
	wxLog::SetActiveTarget(LogFile);
	
	alarmaction.InitAlarm();

	InitControl();

	m_tuxsite.InitSocket(*this, SOCKET_ID);
	m_timer.SetOwner(this,ID_TIMER);
}

TuxSpyPanel::~TuxSpyPanel()
{
	//delete wxLog::SetActiveTarget(LogFile);

	m_logfile.Close();
	dbWrapper.DBClose();

	if(m_IsStart) m_tuxsite.Close();

}

int TuxSpyPanel::GetLicenseType()
{
	if( tuxinitbuff.AgentVersion.Contains(wxT("TRIAL")) ) {
		return -1;
	}

	return 1;
}
void TuxSpyPanel::OnTimer(wxTimerEvent& event)
{
/*
	m_rcvdata = m_tuxsite.ActVsAgent(GETSVRDATA,wxT(""));
	if( SvrDataParser() > 0 ) {
		UpdateControl();
		DoAlarmAction();
    }
*/
	TuxPanelThread* pThread = new TuxPanelThread((TuxSpyPanel*)this);        
	pThread->Create();                      //create new thread
	pThread->Run();
 
} 

void TuxSpyPanel::OnSocketEvent( wxSocketEvent& event)
{
	int flag = m_tuxsite.OnEvent( event );
	if( flag == wxSOCKET_LOST ) { //Detect Connection is broken.
			wxString sysinfo = wxT("Connection to agent is broken!");
			wxDateTime now = wxDateTime::Now();
			wxString crttime = now.Format(wxT("[%y-%m-%d %X]: [WARN]: "),wxDateTime::A_WST);
			m_txtSystem->AppendText(crttime + sysinfo);
			m_timer.Stop();
			m_IsStart = false;
			m_btnControl->SetLabel(wxT("Start"));
			m_txtInterval->Enable(true);
	}
}
void TuxSpyPanel::OnAlarmSet(wxCommandEvent& event )
{
	int n = 0;
	TuxSpyTuxAlarmDlg* alarmSet = new TuxSpyTuxAlarmDlg( this );

	alarmSet->SetTuxAlarm( m_tuxalarm );

	if( alarmSet->ShowModal() != IDOK ) return;
	m_tuxalarm = alarmSet->GetTuxAlarm();

	m_tuxalarm.SiteName = m_site.SiteName;
	dbWrapper.TuxAlarmUpdate(m_tuxalarm);

}

void TuxSpyPanel::OnBtnLogClear( wxCommandEvent& event )
{
	m_txtSystem->Clear();
}
void TuxSpyPanel::OnChsServer( wxCommandEvent& event )
{
	m_chssvrfilter = m_chsServer->GetSelection();

	return;
}
void TuxSpyPanel::OnChsQueue( wxCommandEvent& event )
{
	m_chsquefilter = m_chsQueue->GetSelection();

	return;
	
}
void TuxSpyPanel::OnSvrListColClick( wxListEvent& event )
{
//	wxMessageBox(wxT("Clicked!"));
	
	switch(event.GetColumn())
	{
	case 0:
		break;
	case 1:case 2:
		break;
	case 3: //RqDone
		break;

	}

	return;
}

void TuxSpyPanel::OnSvrFilterCheck( wxCommandEvent& event  )
{
	if( event.IsChecked() ) {
		m_textSvrFilter->Enable();
	} else {
		m_textSvrFilter->Disable();
		m_svrfilter = wxT("*");
	}

}
void TuxSpyPanel::OnSvrFilterApply( wxCommandEvent& event )
{

	if( m_checkBoxSvrFilter->IsChecked() ) {
		m_svrfilter = m_textSvrFilter->GetValue();
	} else {
		;
	}
	return;

}

void TuxSpyPanel::OnQueFilterApply( wxCommandEvent& event )
{	
	if( m_checkBoxQueFilter->IsChecked() ) {
		m_quefilter = m_textQueFilter->GetValue();
	} else {
		;
	}
	return;

}

void TuxSpyPanel::OnQueFilterCheck( wxCommandEvent& event  )
{
	if( event.IsChecked() ) {
		m_textQueFilter->Enable();
	} else {
		m_textQueFilter->Disable();
		m_quefilter = wxT("*");
	}

}
void TuxSpyPanel::StartMonitor() 
{
	int ret = 0;
	int port = 0;
	wxString value;
	wxInt32 interval = 0;
	
	wxChar debugmsg[1024];

	memset( debugmsg, 0, sizeof(wxChar) );

	m_site.SitePort.ToULong((unsigned long*)&port);
	ret = m_tuxsite.Connect(m_site.SiteIP,port);
	if ( ret == -1 ) {
		sprintf( debugmsg, wxT("Connect to Host[%s: %d] Failed!"), m_site.SiteIP, port );
		wxMessageBox( debugmsg );
		return;
	}
	ret = m_tuxsite.HandShake() ;
	if ( ret == -1 ) {
		wxMessageBox( wxT("HandShake to Host Failed!") );
		return;
	}

	value = m_txtInterval->GetValue();
	interval = atoi( value.c_str() ) * 1000;

	if ( interval <  15000 ) {
		wxMessageBox( wxT("Interval can not set below 15!") );
		return;
	}

	m_timer.Start(interval);

	m_IsStart = true;
	oldtuxsvrarray.Empty();	oldtuxquearray.Empty();

	m_btnControl->SetLabel(wxT("Stop"));
	m_txtInterval->Enable(false);
	m_rcvdata = m_tuxsite.ActVsAgent(GETINITDATA,wxT(""));

	for( int i = 0; i< 10; i++ ) {
		m_lstStatus->SetItem(i, 1, wxT("") );
	}

	m_nreccount = 0;

	SvrDataParser();	UpdateControl();

	return;
}
void TuxSpyPanel::StopMonitor()
{
	m_timer.Stop();
	m_tuxsite.Close();
	m_IsStart = false;
	m_btnControl->SetLabel(wxT("Start"));
	m_txtInterval->Enable(true);

	return;
}
void TuxSpyPanel::OnControl( wxCommandEvent& event )
{
	if(  m_IsStart == false ) {
		StartMonitor();
	} else {
		if( wxMessageBox(wxT("Stop a running tuxedo site monitor?"),wxT("Confirm"),wxYES_NO|wxICON_QUESTION) == wxYES ) {
			StopMonitor();
		}
	}

	return;

}

void TuxSpyPanel::SetSite( Site site)
{
	m_site = site;
	// Find the site's Alarm
	wxString StdDataDir = wxStandardPaths::Get().GetDataDir();
	wxString dbname = StdDataDir + wxT("\\") + m_site.DatabaseFile;

	dbWrapper.DBOpen( dbname, TUXTABLE );

	int n = dbWrapper.TuxAlarmListQuery( m_site.SiteName );
	if( n == 0 ){ // New Alarm Setting 
	} else {
		m_tuxalarm = dbWrapper.getTuxAlarm();
	}
}

int TuxSpyPanel::InitControl()
{

	wxInt16 SvrCount = 0;
	long tmp = 0;

	wxListItem itemCol;

	// Server List Init
	for ( int i = 0; !server_list_column[i].IsEmpty(); i ++ ) {
		itemCol.SetText(server_list_column[i]);
		m_lstSvrInfo->InsertColumn(i, itemCol);
	};
	// Queue List Init
	for ( int i = 0; !queue_list_column[i].IsEmpty(); i ++ ) {
		itemCol.SetText(queue_list_column[i]);
		m_lstQueInfo->InsertColumn(i, itemCol);
	};

	// Client List Init
	for ( int i = 0; !client_list_column[i].IsEmpty(); i ++ ) {
		itemCol.SetText(client_list_column[i]);
		m_lstCltInfo->InsertColumn(i, itemCol);
	};

	// Status List Init
	itemCol.SetText(wxT("Statu"));
	m_lstStatus->InsertColumn(0, itemCol);

	itemCol.SetText(wxT("Values"));
	m_lstStatus->InsertColumn(1, itemCol);

	for ( int i = 0; !status_list_value[i].IsEmpty(); i ++ ) {
		m_lstStatus->InsertItem( i, status_list_value[i] );
	};

	for( int i = 0; i< m_lstStatus->GetColumnCount(); i ++ )
		m_lstStatus->SetColumnWidth(i, wxLIST_AUTOSIZE_USEHEADER);

	return 1;

}

void TuxSpyPanel::UpdateControl()
{
	wxInt16 count = 0;
	wxDateTime now = wxDateTime::Now();
	wxString currenttime = now.Format(wxT("%Y-%m-%d %X"),wxDateTime::A_WST);

	//Fill Queue List Ctrl
	count = (wxInt16)tuxquearray.GetCount();
	m_lstQueInfo->Hide();	m_lstQueInfo->DeleteAllItems();
	for( int i = 0,j = 0; i < count ; i ++ ) {
		TuxedoQueue tuxque;
		tuxque = tuxquearray.Item(i);
		if( tuxque.Flag == DISABLE ) continue; //Filter Here.

		long tmp = m_lstQueInfo->InsertItem( j, tuxque.ProgName );
		m_lstQueInfo->SetItemData( tmp, j );

		if( tuxque.Flag & COLOR ){
			m_lstQueInfo->SetItemTextColour(i, *wxRED);
		}
		m_lstQueInfo->SetItem(j, 1, tuxque.QueName);
		m_lstQueInfo->SetItem(j, 2, tuxque.SvrCnt);
		m_lstQueInfo->SetItem(j, 3, tuxque.Queued);

		j ++;
	}
	for( int i = 0; i< m_lstQueInfo->GetColumnCount(); i ++ )
		m_lstQueInfo->SetColumnWidth(i, wxLIST_AUTOSIZE_USEHEADER);

	//Fill Server List Ctrl
	count = (wxInt16)tuxsvrarray.GetCount();
	m_lstSvrInfo->Hide();	m_lstSvrInfo->DeleteAllItems();
	for( int i = 0, j= 0; i < count ; i ++ ) {
		TuxedoServer tuxsvr;
		tuxsvr = tuxsvrarray.Item(i);
		if( tuxsvr.Flag == DISABLE  ) continue; //Filter Here.
		long tmp = m_lstSvrInfo->InsertItem( j, tuxsvr.ProgName );
		m_lstSvrInfo->SetItemData( tmp, j );

		if( tuxsvr.Flag & COLOR ){
			m_lstSvrInfo->SetItemTextColour(i, *wxRED);
		}
		m_lstSvrInfo->SetItem(j, 1, tuxsvr.QueName);
		m_lstSvrInfo->SetItem(j, 2, tuxsvr.ProcessID);
		m_lstSvrInfo->SetItem(j, 3, tuxsvr.RqDone);
		m_lstSvrInfo->SetItem(j, 4, tuxsvr.SvrMin);
		m_lstSvrInfo->SetItem(j, 5, tuxsvr.SvrMax);
		m_lstSvrInfo->SetItem(j, 6, tuxsvr.CurrService);
		m_lstSvrInfo->SetItem(j, 7, tuxsvr.UseMem);

		j ++;
	}
	for( int i = 0; i< m_lstSvrInfo->GetColumnCount(); i ++ )
		m_lstSvrInfo->SetColumnWidth(i, wxLIST_AUTOSIZE_USEHEADER);
	
	//Fill Client List Ctrl
	count = (wxInt16)tuxcltarray.GetCount();
	m_lstCltInfo->Hide();	m_lstCltInfo->DeleteAllItems();

	for( int i = 0; i < count ; i ++ ) {
		TuxedoClient tuxclt;
		tuxclt = tuxcltarray.Item(i);
		long tmp = m_lstCltInfo->InsertItem( i, tuxclt.ClientName );
		m_lstCltInfo->SetItemData( tmp, i );

		m_lstCltInfo->SetItem(i, 1, tuxclt.ClientPID);
		m_lstCltInfo->SetItem(i, 2, tuxclt.ClientAddr);
		m_lstCltInfo->SetItem(i, 3, tuxclt.Status);
		m_lstCltInfo->SetItem(i, 4, tuxclt.ConnectTime);
	}
	for( int i = 0; i< m_lstCltInfo->GetColumnCount(); i ++ )
		m_lstCltInfo->SetColumnWidth(i, wxLIST_AUTOSIZE_USEHEADER);


	m_lstSvrInfo->Show();
	m_lstQueInfo->Show();
	m_lstCltInfo->Show();

	//Update Tuxedo Version
	m_lstStatus->SetItem(0, 1, tuxinitbuff.TuxVersion);
	m_lstStatus->SetItemTextColour(0, *wxRED );
	
	//Update Tuxedo System Boot information
	m_lstStatus->SetItem(1, 1, tuxinitbuff.TuxBootAt );
	m_lstStatus->SetItemTextColour(1, *wxRED );
	
	//Update the last update Time.
	m_lstStatus->SetItem(2, 1, m_lastupdate);

	//Update the Running information.
	m_lstStatus->SetItem(3, 1, tuxstat.ServerCnt);
	m_lstStatus->SetItem(4, 1, tuxstat.QueueCnt);
	m_lstStatus->SetItem(5, 1, tuxstat.ClientCnt);
	
	//Update the system information.
	m_lstStatus->SetItem(6, 1, tuxinitbuff.OSVersion);
	m_lstStatus->SetItem(7, 1, tuxsys.IdleCPU);
	m_lstStatus->SetItem(8, 1, tuxsys.FreeMem);
	m_lstStatus->SetItem(9, 1, tuxinitbuff.AgentVersion);

	for( int i = 0; i< m_lstStatus->GetColumnCount(); i ++ )
		m_lstStatus->SetColumnWidth(i, wxLIST_AUTOSIZE );

	m_tuxresource.sysresource.RecTime = currenttime;
	m_tuxresource.sysresource.CPUIdle = tuxsys.IdleCPU;

	int offset = tuxsys.FreeMem.First('M');
	m_tuxresource.sysresource.MemFree = tuxsys.FreeMem.Left(offset);
	m_tuxresource.TuxRunClt = tuxstat.ClientCnt;
	m_tuxresource.TuxRunQue = tuxstat.QueueCnt;
	m_tuxresource.TuxRunSvr = tuxstat.ServerCnt;


	UpdateLogWindow( 1 );

	// Save Queue/Server/Client Infor into database.
	if( m_chkSaveDB->IsChecked() ) {
		if( GetLicenseType() < 1 && m_nreccount > 10 ) {
			wxMessageBox( TRIAL_LICENSE_WARN );
			m_chkSaveDB->SetValue(false);
		} else {
			if( m_nreccount == 0 ){//Insert Record Vestige
				m_sysreclist.AgentVer = tuxinitbuff.AgentVersion;
				m_sysreclist.OSType = tuxinitbuff.OSVersion;
				m_sysreclist.ProductVer = tuxinitbuff.TuxVersion;
				m_sysreclist.RecTime = currenttime;
				m_sysreclist.SystemBoot =  tuxinitbuff.TuxBootAt ;
				dbWrapper.SysRecListInsert( m_sysreclist );
			}
			if( !m_tuxresource.TuxRunSvr.IsEmpty() ) //if not null save in db
				dbWrapper.TuxResourceInsert( m_tuxresource );
			dbWrapper.TuxQueLstSave( tuxquearray, currenttime );
			dbWrapper.TuxSvrLstSave( tuxsvrarray, currenttime );
			dbWrapper.TuxCltLstSave( tuxcltarray, currenttime );
		}
		m_nreccount ++; if( m_nreccount > 65535) m_nreccount = 1;// reset nRecCount;
	} else {
		m_nreccount = 0;
	}

	return;
}
void TuxSpyPanel::UpdateLogWindow( int type)
{
	wxDateTime now = wxDateTime::Now();

	if ( type == 1 ) {
		wxString sysinfo = tuxsys.CoreFind;
		if( !sysinfo.IsEmpty() && sysinfo.Length() > 5 ) {
			//m_txtSystem->Clear();
			wxString crttime = now.Format(wxT("[%y-%m-%d %X]: [WARN]: "),wxDateTime::A_WST);
			m_txtSystem->AppendText(crttime + sysinfo);
			m_txtSystem->AppendText(wxT("\n"));
			tuxsys.CoreFind.Empty();
		}
		if( !tuxsys.SysReason.IsEmpty() ) { // System is Stop.
			wxString crttime = now.Format(wxT("[%y-%m-%d %X]: [WARN]: "),wxDateTime::A_WST);
			m_txtSystem->AppendText(crttime + tuxsys.SysReason);
			m_txtSystem->AppendText(wxT("\n"));
			tuxsys.SysReason.Empty();
			StopMonitor(); // Force Stoping Monitor;
		}
	} else {	
		if( !m_diedsvrname.IsEmpty() ) {
			wxString crttime = now.Format(wxT("[%y-%m-%d %X]: [WARN]: "),wxDateTime::A_WST);
			m_txtSystem->AppendText(crttime + m_diedsvrname);
			m_txtSystem->AppendText(wxT("\n"));
		}
		if( !m_longbusysvrname.IsEmpty() ) {
			wxString crttime = now.Format(wxT("[%y-%m-%d %X]: [WARN]: "),wxDateTime::A_WST);
			m_txtSystem->AppendText(crttime + m_longbusysvrname);
			m_txtSystem->AppendText(wxT("\n"));
		}
		if( !m_longidlesvrname.IsEmpty() ) {
			wxString crttime = now.Format(wxT("[%y-%m-%d %X]: [WARN]: "),wxDateTime::A_WST);
			m_txtSystem->AppendText(crttime + m_longidlesvrname);
			m_txtSystem->AppendText(wxT("\n"));
		}
	}

}
int TuxSpyPanel::DoAlarmAction()
{
	wxString alartmsg;

	if ( ! m_diedsvrname.IsEmpty() ) {
		m_diedsvrname += wxT(" Died!!!");
		//wxMessageBox(m_diedsvrname);
		alartmsg += m_diedsvrname;
	}
	if ( ! m_longbusysvrname.IsEmpty() ) {
		m_longbusysvrname += wxT(" Busy Too Long!!!");
		//wxMessageBox(m_longbusysvrname);
		alartmsg += m_longbusysvrname;
	}
	if ( ! m_longidlesvrname.IsEmpty() ) {
		m_longidlesvrname += wxT(" Idle Too Long!!!");
		//wxMessageBox(m_longidlesvrname);
		alartmsg += m_longidlesvrname;
	}

	if( m_tuxalarm.PlaySound == wxT("TRUE") && !alartmsg.empty() ) { //Alarm PlayMusic.
		alarmaction.PlayMusic();
	}

	if( m_tuxalarm.SMS == wxT("TRUE") && !alartmsg.empty() ) { //Alarm SendSMS.
		alarmaction.SendSMS(alartmsg);
	}

	if( m_tuxalarm.Email == wxT("TRUE") && !alartmsg.empty() ) { //Alarm Send EMail.
		alarmaction.SendMail(alartmsg);
	}

	UpdateLogWindow( 2 );

	//Initial those alarm messages.
	m_diedsvrname.Empty();	m_longbusysvrname.Empty();
	m_longidlesvrname.Empty();

	return 1;
}
int TuxSpyPanel::SetAlarmType( wxString svrname, int alarmtype )
{
	switch( alarmtype ) {
		case SVRDIED:
			if( !m_diedsvrname.Contains(svrname) )  {
				m_diedsvrname += wxT("[ ");
				m_diedsvrname += svrname;
				m_diedsvrname += wxT("] ");
			}
			break;
		case LONGBUSY:
			if( !m_longbusysvrname.Contains(svrname) ) {
				m_longbusysvrname += wxT("[ ");
				m_longbusysvrname += svrname;
				m_longbusysvrname += wxT("] ");
			}
			break;
		case LONGIDLE:
			if( !m_longidlesvrname.Contains(svrname) )  {
				m_longidlesvrname += wxT("[ ");
				m_longidlesvrname += svrname;
				m_longidlesvrname += wxT("] ");
			}
			break;
		default:
			break;
	}

	return 1;
}


void TuxSpyPanel::AlarmSvrData( )
{
	TuxedoServer oldtuxsvr, tuxsvr;

	if( tuxsvrarray.IsEmpty() && tuxquearray.IsEmpty() ) return;

	if( oldtuxsvrarray.IsEmpty() ) {
		oldtuxsvrarray = tuxsvrarray;
		return;
	}

	if( oldtuxquearray.IsEmpty() ) {
		oldtuxquearray = tuxquearray;
	}

	for ( size_t i = 0; i < oldtuxsvrarray.GetCount(); i ++ ) {
		oldtuxsvr = oldtuxsvrarray.Item(i);
		if( tuxsvrarray.Item(i).ProcessID != oldtuxsvrarray.Item(i).ProcessID ) { //MisMatched!!!
			if( tuxsvrarray.GetCount() < oldtuxsvrarray.GetCount() ) {// New Array Less Than Old 
				if( m_tuxalarm.SvrDied.Contains(oldtuxsvrarray.Item(i).ProgName) ){ //Need To Verify ServerDied
					SetAlarmType( oldtuxsvrarray.Item(i).ProgName, SVRDIED );// To Alarm
				}
			}
		} else { // the same ProcessID
			if( tuxsvrarray.Item(i).RqDone == oldtuxsvrarray.Item(i).RqDone ) { //old and new array the same RqDone.
				if( m_tuxalarm.LongBusy.Contains(oldtuxsvrarray.Item(i).ProgName) ) {//Need To Verify LongBusy
					if( tuxsvrarray.Item(i).CurrService != wxT("IDLE") )  {
						tuxsvrarray.Item(i).Flag |= LONGBUSY;
						tuxsvrarray.Item(i).Flag |= COLOR;
						SetAlarmType( oldtuxsvrarray.Item(i).ProgName, LONGBUSY );
					}
				}
				if( m_tuxalarm.NoTran.Contains(oldtuxsvrarray.Item(i).ProgName) ) {//Need To Verify NoTran
					if( tuxsvrarray.Item(i).CurrService == wxT("IDLE") ) {
						tuxsvrarray.Item(i).Flag |= LONGIDLE;
						tuxsvrarray.Item(i).Flag |= COLOR;
						SetAlarmType( oldtuxsvrarray.Item(i).ProgName, LONGIDLE );
					}
				}
			}
		}

	}

	// Assign old to New Array.
	oldtuxsvrarray = tuxsvrarray;

	return;
}

int TuxSpyPanel::FilterSvrData(wxString svrname, wxString svrstatus, int type)
{
	int status = 0;

	if ( type == 1 ) { //Server Filter
		if( m_svrfilter == wxT("*") ) {
			status =  ENABLE;
		} 
		switch( m_chssvrfilter ) {
			case 0: //All
				break;
			case 1: //Idle
				if( !svrstatus.Contains(wxT("IDLE")) ) status = DISABLE;
				break;
			case 2: //Busy
				if( svrstatus.Contains(wxT("IDLE")) ) status = DISABLE;
				break;
		}
		if( m_svrfilter == wxT("*") ){
			;
		} else {
			if ( m_svrfilter.Contains( svrname ) )
				status = ENABLE; 
			else
				status = DISABLE;
		}

	} else { //Queue Filter
		if( m_quefilter == wxT("*") ) {
			status = ENABLE;
		} 
		switch( m_chsquefilter ) {
			case 0: //All
				break;
			case 1: //Idle
				if( svrstatus != wxT("0") ) status = DISABLE;
				break;
			case 2: //Busy
				if( svrstatus == wxT("0") ) status = DISABLE;
				break;
		}
		if( m_quefilter == wxT("*") ) {
			; 
		}else{
			if	(m_quefilter.Contains( svrname ) )
				status = ENABLE;
			else 
				status = DISABLE;
		}
	}
	return status;
}

int TuxSpyPanel::SvrDataParser()
{
	TuxedoServer tuxsvr;
	TuxedoQueue tuxque;
	TuxedoClient tuxclt;

	wxXmlNode *child;
	wxString content;
	wxXmlDocument doc;

	wxStringInputStream stream( m_rcvdata );

	if( !doc.Load(stream) ) return -1;

	if (doc.GetRoot()->GetName() != wxT("MONITOR"))
    return -1;

	m_lastupdate = doc.GetRoot()->GetPropVal(wxT("Date"), wxT("N/A"));

	tuxsvrarray.Empty();
	tuxquearray.Empty();
	tuxcltarray.Empty();

	child = doc.GetRoot()->GetChildren();

	while( child) {
		if( child->GetName() == wxT("QUEUE") ){
			tuxque.ProgName = child->GetPropVal(wxT("Server"), wxT("N/A"));
			tuxque.QueName = child->GetPropVal(wxT("Queueid"),wxT("N/A"));
			tuxque.SvrCnt = child->GetPropVal(wxT("SrvCnt"), wxT("N/A"));
			tuxque.Queued = child->GetPropVal(wxT("Queued"), wxT("N/A"));
			tuxque.Flag = FilterSvrData( tuxque.ProgName, tuxque.Queued, 0 );
			if( wxAtoi(tuxque.Queued) > wxAtoi(m_tuxalarm.Queued) ) tuxque.Flag |= COLOR;
#ifdef DEBUG
			wxString debugmsg;
			debugmsg.Format(wxT("ProgName:[%s] QueName:[%s] SvrCnt:[%s] Queued:[%s]\n"), 
			tuxque.ProgName, tuxque.QueName, tuxque.SvrCnt, tuxque.Queued);
			wxLogMessage(debugmsg);
#endif
			tuxquearray.Add( tuxque );
			tuxquearray.Sort(SortByQueued); //sort tuxquearray records.
		}

		if( child->GetName() == wxT("SERVER") ){
			tuxsvr.ProgName = child->GetPropVal(wxT("Server"), wxT("N/A"));
			tuxsvr.QueName = child->GetPropVal(wxT("Queueid"),wxT("N/A"));
			tuxsvr.ProcessID = child->GetPropVal(wxT("ProcessID"), wxT("N/A"));
			tuxsvr.RqDone = child->GetPropVal(wxT("RqDone"), wxT("N/A"));
			tuxsvr.CurrService = child->GetPropVal(wxT("CurrSvc"), wxT("N/A"));
			tuxsvr.SvrMin = child->GetPropVal(wxT("SvrMin"), wxT("N/A"));
			tuxsvr.SvrMax = child->GetPropVal(wxT("SvrMax"), wxT("N/A"));
			tuxsvr.UseMem = child->GetPropVal(wxT("UseMem"), wxT("N/A"));
			tuxsvr.Flag = FilterSvrData(tuxsvr.ProgName, tuxsvr.CurrService, 1);

			tuxsvrarray.Add( tuxsvr );
			tuxsvrarray.Sort(SortByRqDone); //sort tuxquearray records.
		}

		if( child->GetName() == wxT("CLIENT") ){
			tuxclt.ClientName = child->GetPropVal(wxT("Name"), wxT("N/A"));
			tuxclt.ClientPID = child->GetPropVal(wxT("ClientPID"),wxT("N/A"));
			tuxclt.ClientAddr = child->GetPropVal(wxT("ClientAddr"), wxT("N/A"));
			tuxclt.Status = child->GetPropVal(wxT("Status"), wxT("N/A"));
			tuxclt.ConnectTime = child->GetPropVal(wxT("ConTime"), wxT("N/A"));
			//tuxclt.Flag = FilterSvrData(tuxclt.ProgName, tuxclt.Status, 1);
			tuxcltarray.Add( tuxclt );

			//tuxsvrarray.Sort(SortByQueued); //sort tuxquearray records.
		}

		if( child->GetName() == wxT("SYSTEM") ){
			tuxsys.CoreFind = child->GetPropVal(wxT("CoreFind"), wxT("N/A"));
			tuxsys.ErrorFind = child->GetPropVal(wxT("ErrorFind"),wxT("N/A"));
			tuxsys.WarnFind = child->GetPropVal(wxT("WarnFind"), wxT("N/A"));
			tuxsys.LargeFile = child->GetPropVal(wxT("LargeFile"), wxT("N/A"));
			tuxsys.FreeMem = child->GetPropVal(wxT("FreeMem"), wxT("N/A"));
			tuxsys.IdleCPU = child->GetPropVal(wxT("IdleCPU"), wxT("N/A"));
			tuxstat.ServerCnt = child->GetPropVal(wxT("SvrCnt"), wxT("N/A"));
			tuxstat.QueueCnt = child->GetPropVal(wxT("QueCnt"), wxT("N/A"));
			tuxstat.ClientCnt = child->GetPropVal(wxT("CltCnt"), wxT("N/A"));

		}
		if( child->GetName() == wxT("ERROR") ) {
			tuxsys.SysReason = child->GetPropVal(wxT("Reason"), wxT("N/A"));
		}

		if( child->GetName() == wxT("INITBUF") ){
			tuxinitbuff.TuxVersion = child->GetPropVal(wxT("TuxVersion"), wxT("N/A"));
			tuxinitbuff.OSVersion = child->GetPropVal(wxT("OSVersion"), wxT("N/A"));
			tuxinitbuff.TuxBootAt = child->GetPropVal(wxT("TuxBootAt"), wxT("N/A"));
			tuxinitbuff.AgentVersion = child->GetPropVal(wxT("AgentVersion"), wxT("N/A"));
		}
		child = child->GetNext();
	}
	//AlarmSvrData( tuxsvrarray, tuxquearray );
	AlarmSvrData( );
	return 1;

}




int SortByQueued(TuxedoQueue** Que1, TuxedoQueue** Que2) {
	wxInt16 Queued = 0, Queued1 = 0;
	Queued = wxAtoi((*Que1)->Queued);
	Queued1 = wxAtoi((*Que2)->Queued);
	return (Queued > Queued1);
}

int SortByRqDone(TuxedoServer** Svr1, TuxedoServer** Svr2)
{
	wxInt16 RqDone = 0, RqDone1 = 0;
	RqDone = wxAtoi((*Svr1)->RqDone);
	RqDone1 = wxAtoi((*Svr2)->RqDone);
	return (RqDone > RqDone1);
}

#include "wx/arrimpl.cpp"
//WX_DEFINE_OBJARRAY(TuxedoServerArray);
//WX_DEFINE_OBJARRAY(TuxedoQueueArray);
//WX_DEFINE_OBJARRAY(TuxedoClientArray);